package unimelb.discussiontracker.twitter.service.integration;

import java.util.Date;

import org.apache.log4j.Logger;

import unimelb.discussiontracker.twitter.data.dao.IIntervalDao;
import unimelb.discussiontracker.twitter.data.dao.IUserDao;
import unimelb.discussiontracker.twitter.data.dao.IUserRankingDao;
import unimelb.discussiontracker.twitter.data.entity.IntervalEntity;
import unimelb.discussiontracker.twitter.data.entity.TopicEntity;
import unimelb.discussiontracker.twitter.data.entity.UserEntity;
import unimelb.discussiontracker.twitter.data.entity.UserRanking;

public class TopUserParser extends AbstractFileProcessor {
    private static final Logger logger = Logger.getLogger(TopHashTagParser.class);

    private IIntervalDao intervalDao;

    private IUserDao userDao;

    private IUserRankingDao userRankingDao;

    public void setIntervalDao(IIntervalDao intervalDao) {
        this.intervalDao = intervalDao;
    }

    public void setUserDao(IUserDao userDao) {
        this.userDao = userDao;
    }

    public void setUserRankingDao(IUserRankingDao userRankingDao) {
        this.userRankingDao = userRankingDao;
    }

    @Override
    protected void processLine(String line, TopicEntity masterTopic) {
        try {
            final String[] tokens = line.split("  ")[0].split(" ");

            final Date start = dateFormat.parse(tokens[0]);
            final Date end = dateFormat.parse(tokens[1]);

            final int strength = Integer.parseInt(tokens[2]);

            final String username = tokens[3];

            final UserEntity user = userDao.findByName(username);
            if (user != null) {
                final IntervalEntity interval = intervalDao.findByStartEnd(start, end);

                UserRanking ranking = userRankingDao.findByUserTopicAndIntervalId(user.getId(), masterTopic.getId(), interval.getId());
                if (ranking == null) {
                    ranking = new UserRanking();
                    ranking.setInterval(interval);
                    ranking.setTopic(masterTopic);
                    ranking.setUser(user);
                    ranking.setStrength(strength);

                    userRankingDao.save(ranking);
                } else {
                    ranking.setStrength(strength);

                    userRankingDao.update(ranking);
                }
            } else {
                logger.info("Unexpected user:" + username);
            }
        } catch (Exception e) {
            logger.error("Invalid line:" + line, e);
        }
    }

}
